<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/4 0004
 * Time: 上午 11:31
 */

namespace common\library\alioss;


use OSS\Core\OssException;
use OSS\OssClient;

class Upload extends OssClient
{
    protected $accessKeyId;
    protected $accessKeySecret;
    protected $endpoint;
    protected $isCName;
    protected $securityToken = null;
    protected $requestProxy = null;
    protected $bucket;

    protected $allow_type = array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf', 'tbi');
    private $max_size = 1024 * 1024 * 3;
    private $default_dir = 'shopnc';

    public function __construct()
    {
        $ali_conf = C('ali_oss');

        $this->accessKeyId = $ali_conf['accessKeyId'];
        $this->accessKeySecret = $ali_conf['accessKeySecret'];
        $this->endpoint = $ali_conf['endpoint'];
        $this->isCName = $ali_conf['isCName'];
        $this->bucket = $ali_conf['bucket'];
        $this->securityToken = $ali_conf['securityToken'];

        parent::__construct($this->accessKeyId, $this->accessKeySecret, $this->endpoint, $this->isCName, $this->securityToken, $this->requestProxy);
    }

    /**
     * 上传图片
     * @author: yanggang
     * @date: 2018/9/4 0004
     * @param $file
     * @param null $fileName
     * @return array
     */
    public function uploadImg($file, $fileName = null)
    {
        $img = $file['tmp_name'];
        $fileName = $fileName ?? str_replace('.', '', uniqid('', true));
        $ext = array_pop(explode('/', $file['type']));

        if (($check = $this->checkImg($file)) !== true) {
            return ['status' => 0, 'msg' => $check];
        }


        try {
            $res = $this->uploadFile($this->bucket, $this->default_dir . '/' . $fileName . '.' . $ext, $img);
        } catch (OssException $e) {
            return ['status' => 0, 'msg' => $e->getMessage()];
        }

        return ['status' => 1, 'msg' => '上传成功', 'data' => $res['oss-request-url']];
    }

    /**
     * 检查图片
     * @author: yanggang
     * @date: 2018/9/4 0004
     * @param $file
     * @return bool|string
     */
    protected function checkImg($file)
    {

        if ($file['size'] > $this->max_size) { // 大小超出限制
            return '大小超出限制';
        }

        if (!($file_info = @getimagesize($file['tmp_name']))) { //不是正确的图片
            return '无法识别的图片';
        }

        $ext = array_pop(explode('/', $file_info['mime']));

        if (!in_array($ext, $this->allow_type)) { //图片类型不符
            return '图片类型不正确';
        }

        return true;

    }


}